package com.im.dispatcher;

import com.im.common.Response;
import com.im.common.ResponseCode;
import com.im.protocol.AuthenticateRequestProto;
import com.im.protocol.AuthenticateResponseProto;

/**
 * @Created leijun
 * @Date 2021/9/20 2:12 下午
 */
public class RequestHandler {

    private RequestHandler() {}

    static class Singleton {
        private static RequestHandler requestHandler = new RequestHandler();
    }

    public static RequestHandler getInstance() {
        return Singleton.requestHandler;
    }

    /**
     * 处理认证请求
     * @param authenticateRequest
     * @return
     */
    public AuthenticateResponseProto.AuthenticateResponse authenticate(
            AuthenticateRequestProto.AuthenticateRequest authenticateRequest) {
        AuthenticateResponseProto.AuthenticateResponse.Builder respBuilder =
                AuthenticateResponseProto.AuthenticateResponse.newBuilder();
        try {
            Long uid = authenticateRequest.getUid();
            String token = authenticateRequest.getToken();
            if (authenticateBySSO(uid, token)) {
                respBuilder.setErrorCode(0);
                respBuilder.setErrorMessage("认证成功");
                respBuilder.setStatus(ResponseCode.OK);
                respBuilder.setUid(uid);
                respBuilder.setToken(token);
                respBuilder.setTimestamp(authenticateRequest.getTimestamp());
            } else {
                respBuilder.setErrorCode(0);
                respBuilder.setErrorMessage("认证失败");
                respBuilder.setStatus(ResponseCode.ERROR);
            }
        } catch (Exception e) {
            respBuilder.setErrorCode(-1);
            respBuilder.setErrorMessage("认证系统响应失败");
        }

        return respBuilder.build();
    }

    private Boolean authenticateBySSO(Long uid, String token) {
        // TODO 调用sso系统进行认证
        return true;
    }
}
